package com.baizhi.serviceImpl;

import com.baizhi.dao.MenuMapper;
import com.baizhi.entity.Menu;
import com.baizhi.repository.MenuRepository;
import com.baizhi.service.MenuService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Resource
    RestHighLevelClient restHighLevelClient;

    @Resource
    MenuMapper menuMapper;

    @Resource
    MenuRepository menuRepository;

    @Override
    public List<Menu> queryAll() {
        return menuMapper.selectList(null);
    }


    public void add(Menu menu) {
        menuRepository.save(menu);
    }


    public void delete(Menu menu) {
        menuRepository.delete(menu);
    }



    public void update(String menuId) {
        //menuRepository.save(menu);
    }

    @Override
    public List<Menu> search(String content) throws IOException {

        //床架处理高亮的对象
        HighlightBuilder highlightBuilder = new HighlightBuilder()
                .preTags("<span style='color:red'>")  //高亮前缀
                .postTags("</span>") //高亮的后缀
                .requireFieldMatch(false) //开启多行高亮
                .field("*");

        //创建搜索条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(QueryBuilders
                        .queryStringQuery(content)  //搜索条件
                        .field("name")  //匹配的字段
                        .field("digest")   //匹配的字段
                        .analyzer("ik_max_word"))  //指定搜索的分词器
                .highlighter(highlightBuilder);    //设置高亮查询

        //创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest()
                .indices("menus")  //设置索引
                .types("menu")  //设置类型
                .source(searchSourceBuilder);  //设置搜索条件 搜索的方式

        //搜索索引  .search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        ArrayList<Menu> menuList = new ArrayList<>();

        //获取命中的数据
        SearchHits hits = searchResponse.getHits();

        SearchHit[] hitss = hits.getHits();

        //获取搜索的数据数组
        for (SearchHit doc : hitss) {

            //获取map数据
            Map<String, Object> sourceAsMap = doc.getSourceAsMap();

            //获取数据
            String id = sourceAsMap.get("id").toString();
            String name = sourceAsMap.get("name").toString();
            String photo = sourceAsMap.get("photo").toString();

            String createDate = sourceAsMap.get("createDate").toString();
            Date createDates =null;
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                createDates = simpleDateFormat.parse(createDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String createPerson = sourceAsMap.get("createPerson").toString();
            String digest = sourceAsMap.get("digest").toString();
            String step = sourceAsMap.get("step").toString();

            //将数据封装为对象
            Menu menu = new Menu(id, name, photo,createDates, createPerson, digest, step);

            Map<String, HighlightField> highlightFields = doc.getHighlightFields();

            if(highlightFields.get("name")!=null){
                String names = highlightFields.get("name").fragments()[0].toString();
                menu.setName(names);
            }

            if(highlightFields.get("digest")!=null){
                String digests = highlightFields.get("digest").fragments()[0].toString();
                menu.setDigest(digests);
            }

            //将封装的对象放入集合
            menuList.add(menu);
        }
        return menuList;
    }

    @Override
    public void clearIndex() {
        menuRepository.deleteAll();
    }

    @Override
    public void addIndex() {

        //查询所有数据
        List<Menu> menus = menuMapper.selectList(null);

        //重新创建索引
        menuRepository.saveAll(menus);
    }



    @Override
    public Menu queryById(String id) {
        Menu menu = menuMapper.selectById(id);
        return menu;
    }

    @Override
    public void insert(Menu menu) {
        menuMapper.insert(menu);
    }

    @Override
    public void delete(String id) {
        menuMapper.deleteById(id);
    }

    @Override
    public void update(Menu menu) {
        menuMapper.updateById(menu);
    }
}
